<template>
  <div class="login-page">
    <!-- 背景层 -->
    <div class="background-layer">
      <img :src="backgroundImage" alt="登录背景" class="background-image" />
    </div>

    <!-- 内容层 -->
    <div class="content-container">
      <el-form
        :model="loginForm"
        :rules="loginRules"
        ref="loginFormRef"
        class="login-form"
        v-if="!showResetPassword"
      >
        <h2 class="form-title">用户登录</h2>

        <el-form-item label="账号" prop="account">
          <el-input v-model="loginForm.account" placeholder="请输入账号" />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>

        <div class="form-actions">
          <el-button type="primary" @click="handleLogin">{{
            loading ? "登录中..." : "登录"
          }}</el-button>
          <el-button @click="toggleResetPassword">忘记密码？</el-button>
        </div>
      </el-form>

      <!-- 重置密码表单 -->
      <el-form
        :model="resetForm"
        :rules="resetRules"
        ref="resetFormRef"
        class="reset-password-form"
        v-else
      >
        <h2 class="form-title">重置密码</h2>

        <el-form-item label="账号" prop="account">
          <el-input v-model="resetForm.account" placeholder="请输入账号" />
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
          <el-input v-model="resetForm.phone" placeholder="请输入手机号" />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="resetForm.email" placeholder="请输入邮箱" />
        </el-form-item>

        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="resetForm.newPassword"
            type="password"
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>

        <el-form-item label="身份证后六位" prop="idCardLastSix">
          <el-input
            v-model="resetForm.idCardLastSix"
            placeholder="请输入身份证后六位"
            show-password
          />
        </el-form-item>

        <div class="form-actions">
          <el-button type="primary" @click="handleResetPassword">{{
            sending ? "重置中..." : "重置密码"
          }}</el-button>
          <el-button @click="toggleResetPassword">返回登录</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import backgroundImage from "@/assets/background.jpg";
import { ElMessage } from "element-plus";
import { useRouter, useRoute } from "vue-router";
import api from "@/api";
import { useUserStore } from "@/stores/user";

const loading = ref(false);
const sending = ref(false);

const router = useRouter();
const route = useRoute();
const userStore = useUserStore();

const loginFormRef = ref(null);
const resetFormRef = ref(null);

const loginForm = reactive({
  account: "",
  password: "",
});

const resetForm = reactive({
  account: "",
  phone: "",
  email: "",
  newPassword: "",
  idCardLastSix: "",
});

const showResetPassword = ref(false);

const loginRules = reactive({
  account: [{ required: true, message: "账号不能为空", trigger: "blur" }],
  password: [{ required: true, message: "密码不能为空", trigger: "blur" }],
});

const resetRules = reactive({
  account: [{ required: true, message: "账号不能为空", trigger: "blur" }],
  phone: [
    { required: true, message: "手机号不能为空", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入有效的手机号",
      trigger: "blur",
    },
  ],
  email: [
    { required: true, message: "邮箱不能为空", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱格式", trigger: "blur" },
  ],
  newPassword: [{ required: true, message: "新密码不能为空", trigger: "blur" }],
  idCardLastSix: [
    { required: true, message: "身份证后六位不能为空", trigger: "blur" },
    {
      pattern: /^\d{6}$/,
      message: "请输入有效的身份证后六位",
      trigger: "blur",
    },
  ],
});
const handleLogin = async () => {
  try {
    loading.value = true;
    if (loginForm.account == null) {
      ElMessage.error("账号不能为空");
    }
    if (loginForm.password == null) {
      ElMessage.error("密码不能为空");
    }

    // 调用接口（注意结构变化）
    const { data: token } = await api.auth.login(loginForm);

    // 验证Token格式
    if (typeof token !== "string" || !token.includes(".")) {
      throw new Error("无效的Token格式");
    }

    // 存储Token
    localStorage.setItem("token", token);
    userStore.setToken(token);
    console.log("Store Token:", userStore.token);
    console.log("存储的Token:", localStorage.getItem("token"));
    await userStore.fetchUserInfo();
    console.log(
      "登录用户信息:",
      JSON.parse(JSON.stringify(userStore.userInfo))
    );
    // 路由跳转（增加错误捕获）
    const redirectPath = route.query.redirect || "/";
    await router.push(redirectPath).catch(() => {
      router.replace("/"); // 容错处理
    });
    router.replace(route.query.redirect || "/");
  } catch (error) {
    ElMessage.error("登录失败");
  } finally {
    loading.value = false;
  }
};

const handleResetPassword = async () => {
  await resetFormRef.value.validate();
  try {
    sending.value = true;

    const params = {
      ...resetForm,
      identityVerification: {
        phone: resetForm.phone,
        email: resetForm.email,
        idCardSuffix: resetForm.idCardLastSix,
      },
    };
    const { data } = await api.auth.resetPwd(params);
    console.log("重置密码结果:", data);
    // 处理成功逻辑
    ElMessage.success("密码重置成功，请重新登录");
    showResetPassword.value = !showResetPassword.value;
  } catch (error) {
    console.error("密码重置失败:", error);

    // 错误分类处理
    const errorMessage =
      error.response?.data?.message || error.message || "密码重置失败";

    if (error.response?.status === 404) {
      ElMessage.error("用户信息不匹配");
    } else if (error.response?.status === 400) {
      ElMessage.error("验证信息有误");
    } else {
      ElMessage.error(errorMessage);
    }
  } finally {
    sending.value = false;
  }
};

const toggleResetPassword = () => {
  showResetPassword.value = !showResetPassword.value;
};
</script>

<style scoped lang="css">
.login-page {
  position: relative;
  min-height: 100vh;
}

.background-layer {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 0;
}

.background-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  filter: brightness(0.92) blur(2px);
}

.content-container {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 1;
  max-width: 400px;
  padding: 40px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
}

.login-form,
.reset-password-form {
  width: 100%;
}

.form-title {
  font-size: 1.8rem;
  color: #2c3e50;
  text-align: center;
  margin-bottom: 30px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #34495e !important;
}

:deep(.el-input__inner) {
  background: #f8f9fa;
  border-radius: 6px;
}

.form-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 30px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .content-container {
    padding: 30px;
  }

  .form-title {
    font-size: 1.5rem;
  }
}
</style>
